package com.cinema.dao;

import java.sql.*;
import java.util.*;
import java.io.*;

import com.mysql.jdbc.PreparedStatement;

public class BaseDao {
	private String Driver_Class = "";
	private String Url = "";
	private String User = "";
	private String Pwd = "";

	// 内部枚举
	public enum ChangeType {
		UPDATE, DELETE, INSERT;
	}

	public BaseDao() {
		load();
	}

	// 加载驱动
	public void load() {
		if (Driver_Class.trim().length() == 0) {
			// 读取配置文件，识别我的数据库驱动,读入
			Properties pro = new Properties();
			try {
				// 得到BaseDao的类型，再得到类加载器，再去相对定位
				InputStream is = BaseDao.class.getClassLoader()
						.getResourceAsStream("com/cinema/dao/config.properties");
				pro.load(is);
				Driver_Class = pro.getProperty("Driver_Class");
				Url = pro.getProperty("Url");
				User = pro.getProperty("User");
				Pwd = pro.getProperty("Pwd");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			Class.forName(Driver_Class);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Connection getCon() {
		try {
			return DriverManager.getConnection(Url, User, Pwd);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 通用更新方法 需要执行的代码 args参数列表，替换？占位符
	 * */
	protected int change(String sql, String[] args) {
		Connection con = getCon();
		try {
			PreparedStatement pstmt = (PreparedStatement) con
					.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				pstmt.setString(i + 1, args[i]);
			}
			return pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static void main(String[] args) {
		BaseDao base = new BaseDao();
		System.out.println(base.getCon());
	}
}
